<template>
    <div class="pdf-sign-body">
        <div>
            <div class="my-sign">
                <h3>我的签名</h3>
                <div v-for="(item,index) in signList" class="sign-img" :key="index">
                    <img loading="lazy" :id="'signimg_'+index" :src="item.src" draggable="true" @dragstart="ondragstart">
                    <i class="delete-sign el-icon-delete" @click="$emit('onDeleteSign',item)"/>
                </div>
                <div v-if="signList.length===0" class="sign-empty">您目前没有可使用的签名</div>
                <div class="add-sign-btn">
                    <el-button size="mini" type="primary" @click="$emit('addSign')" icon="el-icon-circle-plus-outline">添加签名</el-button>
                </div>
            </div>
        </div>
        <div v-if="pdfSrc" @drop="ondrop" @dragover.stop="ondragover" ref="pdfviews" class="pdf-views" @scroll="onScroll">
             <pdf
            v-for="(i,index) in numPages"
            :key="index"
            :data-page="index"
            :src="pdfSrc"
            :page="i"
            :style="'width:'+width+'px'"
            :class="`pdf-pages pdf_${index}`"
            ></pdf>
        </div>
        <div v-else class="pdf-empty" :style="'width:'+width+'px'">PDF文件加载失败</div>
        <div class="pdf-page-tips">{{currentPage}} / {{pageCount || 1}}</div>
    </div>
</template>
<script>

import pdf from 'vue-pdf'
import { Button } from 'element-ui'
export default {
  components: {
    pdf,
    ElButton: Button
  },
  props: {
    pdfUrl: {
      type: String,
      default: 'http://localhost:8081/file/contract/惠州炬威电子有限公司销售合同C300-1840-21-11.10.pdf'
    },
    signList: {
      type: Array,
      default: () => []
    },
    width: {
      type: Number,
      default: 800
    },
    getSigned: {
      type: Boolean,
      default: false
    }
  },
  data () {
    return {
      numPages: 1,
      pdfSrc: '',
      currentPage: 1,
      pageCount: 0,
      imgObj: {
        clientWidth: 0,
        clientHeight: 0
      },
      oldOffsetX: 0,
      oldOffsetY: 0,
      nowImgId: '',
      signedList: [],
      scale: 0
    }
  },
  watch: {
    pdfUrl: {
      handler (val) {
        if (val) {
          this.pdfSrc = this.pdfUrl
        }
      },
      immediate: true
    },
    getSigned: {
      handler (val) {
        if (val) this.$emit('onSignedList', this.signedList)
      }
    }
  },
  created () {
    // if(this.pdfUrl && !this.pdfSrc) this.pdfSrc = pdf.createLoadingTask(this.pdfUrl);
    // console.log(this.pdfUrl)
    // if (this.pdfUrl) this.pdfSrc = pdf.createLoadingTask(this.pdfUrl)
  },
  mounted () {
    this.getPdfData()
    document.addEventListener('click', function () {
      const signed = document.querySelector('.signed')
      if (signed) signed.classList.add('heid-drag')
    })
  },
  methods: {
    getPdfData () {
      console.log('this.pdfSrc', this.pdfSrc)
      if (!this.pdfSrc) return
      // eslint-disable-next-line no-shadow
      this.pdfSrc = pdf.createLoadingTask(this.pdfSrc)
      this.pdfSrc.promise.then(res => {
        // this.pdfDoc = pdf;
        this.numPages = res.numPages
      })
    },
    onScroll (e) {
      this.debounce(this.getPageCode(e), 1000)
    },
    debounce (fn, wait) {
      var timeout = null
      return function () {
        if (timeout !== null) clearTimeout(timeout)
        timeout = setTimeout(fn, wait)
      }
    },
    getPageCode (e) {
      this.currentPage = Math.floor(e.target.scrollTop / (e.target.scrollHeight / this.numPages)) + 1
    },
    // 拖拽开始
    ondragstart (e) {
      this.nowImgId = e.target.id
      this.imgObj = {
        clientHeight: e.target.clientHeight,
        clientWidth: e.target.clientWidth
      }
    },
    handleDrag (e) {
      if (this.oldOffsetX === e.offsetX && this.oldOffsetY === e.offsetY) return
      const dom = document.querySelector('#' + e.target.parentNode.id)
      dom.style.width = (e.target.offsetLeft + 7 + e.offsetX) + 'px'
      dom.style.height = (e.target.offsetTop + 7 + e.offsetY) + 'px'
      this.oldOffsetX = e.offsetX
      this.oldOffsetY = e.offsetY
    },
    // 拖拽放置
    ondrop (e) {
      e.preventDefault()
      // if(e.target.id) return null;
      const { clientWidth, clientHeight } = this.imgObj
      if (this.nowImgId.includes('signimg_')) {
        // 拖拽新签名
        const newImg = document.createElement('div')
        const img = document.querySelector('#' + this.nowImgId)
        // eslint-disable-next-line no-shadow
        newImg.onclick = function (e) {
          e.preventDefault()
          e.stopPropagation()
          document.querySelector('#' + e.target.id).classList.remove('heid-drag')
        }
        // 添加id
        const className = document.getElementsByClassName('signed')
        newImg.id = 'signed_' + (1 + className.length||0)
        // 添加class
        const nowPage = e.target.offsetParent.className.split('pdf_')[1]
        newImg.className = 'signed signed_' + nowPage
        newImg.style.background = `url(${img.src}) no-repeat center center`
        newImg.style.backgroundSize = '100% 100%'
        newImg.style.position = 'absolute'
        newImg.style.width = clientWidth + 'px'
        newImg.style.height = clientHeight + 'px'

        newImg.draggable = 'true'
        newImg.ondragstart = this.ondragstart
        const position = this.getTopLeft(e)
        newImg.style.top = position.top + 'px'
        newImg.style.left = position.left + 'px'
        // 创建删除图标
        const Delete = document.createElement('div')
        Delete.className = 'delete-drag el-icon-delete'
        // eslint-disable-next-line no-shadow
        Delete.onclick = function (e) {
          e.preventDefault()
          e.stopPropagation()
          e.target.parentNode.parentNode.removeChild(e.target.parentNode)
        }
        newImg.appendChild(Delete)
        // 创建重置尺寸图标
        const Resize = document.createElement('div')
        Resize.className = 'resize-block'
        Resize.draggable = 'true'
        Resize.id = 'resize_' + (1 + className.length)
        Resize.ondrag = this.handleDrag
        Resize.ondragstart = this.ondragstart
        newImg.appendChild(Resize)
        e.target.appendChild(newImg)
        const obj = {
          signedId: newImg.id,
          page: e.target.parentNode.dataset.page,
          width: clientWidth,
          height: clientHeight,
          top: position.top,
          left: position.left
        }
        this.signedList.push(obj)
      } else if (this.nowImgId.includes('signed_')) {
        const page = e.target.parentNode.dataset.page
        if (!page) return
        // // 原签名拖拽
        const nowImg = document.querySelector('#' + this.nowImgId)
        const position = this.getTopLeft(e)
        nowImg.style.top = position.top + 'px'
        nowImg.style.left = position.left + 'px'

        const oldPge = nowImg.parentNode.parentNode.dataset.page
        if (oldPge !== page) {
          nowImg.parentNode.removeChild(nowImg)
          e.target.appendChild(nowImg)
        }

        this.signedList.forEach(i => {
          if (i.signedId === this.nowImgId) {
            i.page = e.target.parentNode.dataset.page
            i.top = position.top
            i.left = position.left
          }
        })
      } else if (this.nowImgId.includes('resize_')) {
        // 尺寸改变 记录尺寸
        const nowImg = document.querySelector('#' + this.nowImgId)
        this.signedList.forEach(i => {
          if (i.signedId === nowImg.parentNode.id) {
            i.width = nowImg.parentNode.clientWidth
            i.height = nowImg.parentNode.clientHeight
          }
        })
      }
    },
    // 获取签名图片偏移量
    getTopLeft (e) {
      const { clientWidth, clientHeight } = this.imgObj
      const top = e.offsetY - (clientHeight / 2)
      const left = e.offsetX - (clientWidth / 2)
      const pageHeight = document.querySelector('.pdf-pages').clientHeight
      return {
        // eslint-disable-next-line no-nested-ternary
        top: top < 0 ? 0 : top > pageHeight - clientHeight ? pageHeight - clientHeight : top,
        // eslint-disable-next-line no-nested-ternary
        left: left < 0 ? 0 : left > this.width - clientWidth ? this.width - clientWidth : left
      }
    },
    // 拖拽
    ondragover (e) {
      e.preventDefault()
    }
  }
}
</script>
<style lang="scss" scoped>
.signed{
    border: 1px dashed #ccc;
    cursor: pointer;
    &:hover{
        border-color: #409EFF;
    }
}
.heid-drag{
    border:none;
    &:hover{
        border:1px dashed #409EFF;
        .resize-block{
            display: block;
        }
        .delete-drag{
            display: block;
        }
    }
    .resize-block{
        display: none;
    }
    .delete-drag{
       display: none;
    }
}
.resize-block{
    position: absolute;
    cursor: se-resize;
    bottom: -3px;
    right: -3px;
    width: 12px;
    height: 12px;
    border: 1px solid #ccc;
    background: #fff;
}
.delete-drag{
    position: absolute;
    top: -18px;
    right: -2px;
    padding: 2px;
    color: #F56C6C;
}
</style>
<style lang="scss" scoped>
.pdf-sign-body{
    position: relative;
    display: flex;
    width: 100%;
    height: 100%;
    >div:nth-of-type(1){
        padding: 10px 25px;
        box-sizing: border-box;
        flex: 0 0 400px;
    }
    .my-sign{
        padding: 30px;
        max-height: calc(100% - 50px);
        border: 1px solid #ccc;
        box-shadow: 0 0 8px #ccc;
        background-color: #fff;
        overflow: auto;
        .sign-img{
            position: relative;
            display: flex;
            align-items: center;
            justify-content: center;
            margin: 20px auto;
            width: 100%;
            height: 200px;
            cursor: pointer;
            border: 1px solid #ccc;
            .delete-sign{
                position: absolute;
                top: 10px;
                right: 10px;
                cursor: pointer;
                font-size: 20px;
                color: #F56C6C;
                display: none;
                &:hover{
                    color: red;
                }
            }
            &:hover{
            border-color: #409EFF;
            .delete-sign{
                display: block;
            }
            }
            img{
                max-width: 150px;
                max-height: 300px;
            }
        }
        .sign-empty{
            height: 60px;
            line-height: 60px;
            text-align: center;
        }
        .add-sign-btn{
            text-align: center;
        }
    }
    .pdf-views{
        flex: 1;
        margin-top: 10px;
        position: relative;
        padding: 0;
        display: inline-block;
        overflow: auto;
        &::-webkit-scrollbar {
            /*滚动条整体样式*/
            width: 10px;  /*高宽分别对应横竖滚动条的尺寸*/
            height: 1px;
        }
        &::-webkit-scrollbar-thumb {
            /*滚动条里面小方块*/
            border-radius: 10px;
            box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.1);
            background: #ccc;
        }
        &::-webkit-scrollbar-track {
            /*滚动条里面轨道*/
            box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.1);
            // border-radius: 10px;
            background: #ededed;
        }
    }

    .pdf-pages{
        border-bottom: 1px solid #ccc;
        margin-left: 8px;
        box-shadow: 0 0 8px #ccc;
    }
    .pdf-page-tips{
        position: absolute;
        top: 30px;
        right: 80px;
        font-size: 18px;
    }
    .pdf-empty{
        margin-top: 10px;
        padding-top: 210px;
        box-sizing: border-box;
        text-align: center;
        font-size: 16px;
        color: #b2b2b2;
        margin-left: 8px;
        height: calc(100% - 80px);
        box-shadow: 0 0 8px #ccc;
        background: #fff url(../../assets/empty.jpg) no-repeat center 100px;
        background-size: 100px 100px;
    }
}
</style>
